package de.QuizCommunity;

import java.util.ArrayList;
import java.util.List;

import de.QuizCommunity.maps.GPSTracker;
import de.QuizCommunity.maps.GoogleParser;
import de.QuizCommunity.maps.Parser;
import de.QuizCommunity.maps.Route;

import de.QuizCommunity.maps.RouteOverlay;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;

import de.QuizCommunity.domain.Antwort;
import de.QuizCommunity.util.AppVariabels;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.widget.Toast;

public class Maps_Joker extends MapActivity {

	AppVariabels appVar = AppVariabels.getInstance();
	
	GPSTracker gps;
	
	GeoPoint geoPoint;
	
	int color = Color.BLACK;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps__joker);
        
        MapView mapJoker = (MapView) findViewById(R.id.mapViewJoker);
        gps = new GPSTracker(this);
        
        if (gps.getLocation() == null) {
        	Toast.makeText(this, "Joker ist deaktiviert", Toast.LENGTH_SHORT).show();
        	return;
        }
        else {
        //aktueller Standort ermitteln
        geoPoint = new GeoPoint((int) (gps.getLatitude() * 1E6),
     							(int) (gps.getLongitude() * 1E6));
        
        mapJoker = (MapView) findViewById(R.id.mapViewJoker);
        mapJoker.setBuiltInZoomControls(true);
        mapJoker.setSatellite(false);
        MapController mc = mapJoker.getController();
        mc.animateTo(geoPoint);
        
        int frageId = getIntent().getIntExtra("FrageId", 1) - 1;
        
        de.QuizCommunity.domain.Frage frage = AppVariabels.lstFrage.get(frageId);//AppVariabels.lstFrage.size()-1);
        
        List<Antwort> antworten = frage.getAntwortList();
        
        Drawable markerStandort = this.getResources().getDrawable(R.drawable.mark_blue);
        
        MyItemizedOverlay itemizedOverlay = new MyItemizedOverlay(markerStandort);

        Drawable markerAntwort = this.getResources().getDrawable(R.drawable.mark_red);
        
        itemizedOverlay.addOverlayItem(geoPoint.getLatitudeE6(), geoPoint.getLongitudeE6(), "aktueller Standort", markerStandort);
        for (Antwort a : antworten) {
        	try {
				Log.d("Antwort" + a.getAntworttext(), "Lat: " + String.valueOf((a.getLatitude()*1E6) + " Lon: " + String.valueOf((a.getLongitude()*1E6))));
				Route route = directions(geoPoint, new GeoPoint((int)(a.getLatitude()*1E6),(int)(a.getLongitude()*1E6)));
				RouteOverlay routeOverlay = new RouteOverlay(route, changeColor());
				itemizedOverlay.addOverlayItem((int) (a.getLatitude() * 1E6), (int) (a.getLongitude() * 1E6), a.getAntworttext() + "\n" + zeitBerechnung((int) route.getLength()), markerAntwort);
				mapJoker.getOverlays().add(routeOverlay);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }      
        mapJoker.getOverlays().add(itemizedOverlay);
        }
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.id.mapViewJoker, menu);
        return true;
    }

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	private int changeColor() {
		if (color == Color.BLACK) {
			color = Color.GREEN;
			return color;
		}
		else if (color == Color.GREEN) {
			color = Color.RED;
			return color;
		}
		else {
			color = Color.BLACK;
			return color;
		}
	}
	
	public String zeitBerechnung(int meter) {
		double gehenTempoSek = 1.4;
		int zeit = (int) (meter / gehenTempoSek);
		int stunde = zeit / (60*60);
		int minute = zeit / 60 - (stunde*60);
		int sekunde = zeit % 60;
	    return String.format(stunde + "h:%02dm:%02ds", minute, sekunde);
	}
	
	private Route directions(final GeoPoint start, final GeoPoint dest) {
        Parser parser;
        String jsonURL = "http://maps.google.com/maps/api/directions/json?";
        final StringBuffer sBuf = new StringBuffer(jsonURL);
        sBuf.append("origin=");
        sBuf.append(start.getLatitudeE6()/1E6);
        sBuf.append(',');
        sBuf.append(start.getLongitudeE6()/1E6);
        sBuf.append("&destination=");
        sBuf.append(dest.getLatitudeE6()/1E6);
        sBuf.append(',');
        sBuf.append(dest.getLongitudeE6()/1E6);
        sBuf.append("&sensor=true&mode=walking");
        parser = new GoogleParser(sBuf.toString());
        Route r =  parser.parse();
        return r;
    }
	
	 private class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {

	        private List<OverlayItem> mOverlays = new ArrayList<OverlayItem>();

	        public MyItemizedOverlay(Drawable defaultMarker) {
	            super(boundCenterBottom(defaultMarker));
	        }

	        public void addOverlayItem(int lat, int lon, String title, Drawable altMarker) {
	            GeoPoint point = new GeoPoint(lat, lon);
	            OverlayItem overlayItem = new OverlayItem(point, title, null);
	            addOverlayItem(overlayItem, altMarker);
	        }

	        public void addOverlayItem(OverlayItem overlayItem) {
	            mOverlays.add(overlayItem);
	            populate();
	        }

	        public void addOverlayItem(OverlayItem overlayItem, Drawable altMarker) {
	            overlayItem.setMarker(boundCenterBottom(altMarker));
	            addOverlayItem(overlayItem);
	        }

	        @Override
	        protected OverlayItem createItem(int i) {
	            return mOverlays.get(i);
	        }

	        @Override
	        public int size() {
	            return mOverlays.size();
	        }

	        @Override
	        protected boolean onTap(int index) {
	            Toast.makeText(Maps_Joker.this, getItem(index).getTitle(), Toast.LENGTH_LONG).show();
	            return true;
	        }
	       

	    }
}
